package default_package;
import java.awt.Toolkit;
import java.io.*;
import java.net.*;
import java.util.Date;
import java.util.Scanner;

public class HTTPServer {
	
public static void main(String argv[]) throws Exception {
	ServerSocket server = new ServerSocket(6789);
	while(true) {
		Socket connectionSocket = server.accept();
		BufferedReader inFromClient = new BufferedReader(new
		InputStreamReader (connectionSocket.getInputStream()));
		PrintWriter outToClient = new PrintWriter(connectionSocket.getOutputStream());

		String clientSentence = inFromClient.readLine();
		System.out.println(clientSentence);
		outToClient.print("Echo: " + clientSentence + "\n");
		outToClient.flush();
		String[] words = InputParser.parse(clientSentence);
		String command = words[0];
		if(words.length != 3) {
			outToClient.print("400 Bad request\r\n\r\n");
			outToClient.flush();
		}
		else {
			String filePath = InputParser.getFilePath(words[1]);

			execute(command, filePath, words[2], outToClient, inFromClient);
		}

	connectionSocket.shutdownInput();
	connectionSocket.shutdownOutput();

	System.out.println("Received: " + clientSentence);
}
}

private static void execute(String command, String uri, String HTTPVersion, 
		PrintWriter out, BufferedReader inFromClient) {
	String responseToClient = "";
	if(command.equals("HEAD"))
		responseToClient = HEAD(uri, HTTPVersion, inFromClient);
	else if(command.equals("GET"))
		responseToClient = GET(uri, HTTPVersion, inFromClient);
	else if(command.equals("PUT"))
		responseToClient = PUT(uri, getPutVariables(inFromClient)[1], HTTPVersion);
	else if(command.equals("POST"))
		responseToClient = POST(uri,getPutVariables(inFromClient)[1], HTTPVersion);
	else
		responseToClient = (HTTPVersion + " 400 Bad request");
	
	
	out.print(responseToClient + "\r\n\r\n");
	out.flush();
}

private static String GET(String uri, String HTTPVersion, BufferedReader inputStream) {
	File file = searchFile(uri);
	String response = "";
	if(file == null)
		response = (HTTPVersion +" 404 Not found\n");
	else {
		Scanner scanner;
		try {
			response += HEAD(uri, HTTPVersion, inputStream);
			scanner = new Scanner(file);
			while(scanner.hasNext())
			response += scanner.nextLine();
		} catch (FileNotFoundException e) {	}
	}
	return response;
}

private static String HEAD(String uri, String HTTPVersion, BufferedReader inputStream) {
	String headers = readBlock(inputStream);
	String response = "";
	File file = searchFile(uri);
	if(file == null) 
		return (HTTPVersion + " 404 Not Found\n");
	// add status line
	response += (HTTPVersion + " 200 OK\n");
	// add last modified
	response += ("Last modified : " + (new Date(file.lastModified())).toString() + "\n");
	// add content type
	response += ("Content type : " + "text/html\n");
	// add content length
	response += ("Content length : " + file.length() + "\n");
	// add blank line
	response += ("\n");
	return response;
}

private static String[] getPutVariables(BufferedReader inputStream) {
	String headers = "";
	String content = "";
	headers = readBlock(inputStream);
	content = readBlock(inputStream);
	String[] putVariables = new String[2];
	putVariables[0] = headers;
	putVariables[1] = content;
	return putVariables;
}

private static String PUT(String uri, String content, String HTTPVersion) {
	try {
		System.out.println(uri);
		File temp = new File("src/html_files/" + uri);
		String response;
		if(content == null || content.equals("\r\n")) {
			return (HTTPVersion + " 204 No content \n");
		}
		if(searchFile(uri) == null) {
			temp.createNewFile();
			response = (HTTPVersion + " 201 Created \n");
		}
		else {
			response = (HTTPVersion + " 200 OK \n");
		}
	
		FileWriter fw = new FileWriter(temp.getAbsoluteFile());
		BufferedWriter bw = new BufferedWriter(fw);
		bw.write(content);
		System.out.println(temp.getAbsolutePath());
		bw.flush();
		bw.close();
		return response;
	}
	catch (IOException e) { System.out.println(e); return null;}
}

private static String POST(String uri, String content, String HTTPVersion) {
	File temp = new File("src/html_files/" + uri);
	Scanner scanner;		
	String originalText = "";
	try {
		scanner = new Scanner(temp);
		while(scanner.hasNext())
		originalText += scanner.nextLine();
		scanner.close();
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	}
	String modifiedText = originalText + "\r\n";
	modifiedText += content;
	return PUT(uri,modifiedText, HTTPVersion);
}
private static File searchFile(String name) {
	File[] files = new File("src/html_files").listFiles();
	for(File file : files) {
		if(file.getName().equals(name))
			return file;
	}
	return null;
}

private static String readBlock(BufferedReader inputStream) {
	String textBlock = "";
	String temp;
	try {
		boolean reading = true;
		while (reading) {
		temp = inputStream.readLine();
		System.out.println(temp);
		if(temp.equals(""))
			reading = false;
		textBlock += (temp + "\r\n");
		}		
	}
	catch(IOException e) { System.out.print(e); }
	return textBlock;
}
}